package net.Stratus.ImageDumper.Dumper;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Random;

public class Internet {
	
	private static String[] userAgents = 
		{"Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:50",
		 "IE 7 ? Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)2011-10-16 20:20:09",
		 "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.23) Gecko/20110920 Firefox/3.6.23 SearchToolbar/1.22011-10-16 20:20:07",
		 "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; InfoPath.2; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 1.1.4322)2011-10-16 20:22:33",
		 "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0"};
	
	private static Random rand = new Random();
	
	public static boolean urlToFile(String url, File file) {
		try {
			// create temp file
			File temp = new File(file.getAbsolutePath()+".temp");
			temp.createNewFile();			
			// of you can't write, this whole thing is pointless
			if(!temp.canWrite()) return false;
			// open http connection
			URL ur = new URL(url);
			URLConnection con = ur.openConnection();
			con.setRequestProperty ("User-agent", randomUserAgent());
			BufferedInputStream in = new BufferedInputStream(con.getInputStream());
			// open file for writing
			FileOutputStream fs = new FileOutputStream(temp);
			// get data from http stream, write to file
			int read;
			byte[] buffer = new byte[10240];
			while ((read = in.read(buffer)) != -1)   {
				fs.write(buffer, 0, read);
			}
			// close everything up
			fs.flush();
			fs.close();
			in.close();	
			temp.renameTo(file);
			return true;
		} catch (IOException e) {
			return false;
		}		
	}
	
	public static String httpRequest(String url) {
		try {
			// open url connection
			URL ur = new URL(url);
			URLConnection con = ur.openConnection();
			con.setRequestProperty ("User-agent", randomUserAgent());
	        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
	        // http stream to string
	        StringBuilder sb = new StringBuilder();	
	        int read;
			char[] buffer = new char[1024];
	        while ((read = in.read(buffer)) != -1)   {
				sb.append(buffer, 0, read);
			}
	        // close everything up
	        in.close();
	        return sb.toString();
		} catch (Exception e) {
		}
		return null;		
	}
	
	private static String randomUserAgent() {
		return userAgents[rand.nextInt(userAgents.length)];
	}
}
